<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="客户名称查询"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.BHBH"
          placeholder="保函编号"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开函日期"
          end-placeholder="开函日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="params['ZTMJ.eq']"
          placeholder="项目状态选择"
          clearable
          number-key
          :options="enumLoadStatus"
          @change="getData()"
        ></c-select>
      </el-form-item>

      <el-form-item>
        <c-select
          v-model="params['BHLXMJ.eq']"
          placeholder="保函类型"
          clearable
          number-key
          :options="enumBHType"
          @change="getData()"
        ></c-select>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-plus" @click="handlerEdit()">新增</el-button>
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-upload2" @click="importVisible = true">导入台账</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('保函台账')"
        >
          台账下载
        </el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData"></c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>
    <import-excel
      title="导入保函台账"
      :visible.sync="importVisible"
      :post-api="importUrl"
      :excel-template="importFileUrl"
      @success="getData(params.index)"
    ></import-excel>

    <ledger-letter-edit
      :visible.sync="editVisible"
      :table-id="tableId"
      :form-data="formData"
      @success="getData(params.index)"
    ></ledger-letter-edit>
  </div>
</template>

<script>
import { lastPickerShortcuts, nextPickerShortcuts } from '@/common/plugins/tools/date'
import ImportExcel from '@/components/ImportExcel'
import { queryTrouble } from '@vimi/utils-api'
import { mapGetters } from 'vuex'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'
import LedgerLetterEdit from '@/credit/views/city/reportCity/ledger/component/LedgerLetterEdit'
export const enumBHType = {
  1: '招投标',
  2: '诉讼保全',
  3: '应付款保函',
  4: '预付款保函',
}
export const enumLoadStatus = {
  1: '在保',
  2: '解保',
}
export default {
  components: {
    ImportExcel,
    LedgerLetterEdit,
  },
  props: {},
  data() {
    return {
      enumBHType,
      enumLoadStatus,
      importVisible: false,
      params: {
        index: 1,
        size: 10,
      },
      loading: false,
      tableName: 'BHTZ',
      order: {
        create_time: 'desc',
      },
      datePicked: [],
      pickerOptions: {
        shortcuts: [...lastPickerShortcuts, ...nextPickerShortcuts],
      },
      totalCount: 0,
      tableData: [],
      importKey: 'BHTZ_template',
      tableColumns: [
        { attrs: { label: '客户名称', prop: 'QYMZ', align: 'center' } },
        { attrs: { label: '证件号', prop: 'ZJH', align: 'center' } },
        { attrs: { label: '联系人', prop: 'LXR', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'LXDH', align: 'center' } },
        { attrs: { label: '对方单位', prop: 'DFDW', align: 'center' } },
        { attrs: { label: '保函类型', prop: 'bhType', align: 'center' } },
        { attrs: { label: '保函金额(万元)', prop: 'BHJE', align: 'center' } },
        { attrs: { label: '保函编号', prop: 'BHBH', align: 'center' } },
        { attrs: { label: '担保费率(%)', prop: 'DBFL', align: 'center' } },
        { attrs: { label: '担保费用', prop: 'DBFY', align: 'center' } },
        { attrs: { label: '开函时间', prop: 'KHSJ', align: 'center', width: 100 } },
        { attrs: { label: '到期时间', prop: 'DQSJ', align: 'center', width: 100 } },
        { attrs: { label: '解除时间', prop: 'JCSJ', align: 'center', width: 100 } },
        { attrs: { label: '项目状态', prop: 'loadStatus', align: 'center' } },
        {
          attrs: { label: '操作', align: 'center', width: 100, fixed: 'right' },
          operations: [
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handlerEdit,
              ifRender: row => +row.SFLS === 1,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger' },
              event: this.handlerDelete,
              ifRender: row => +row.SFLS === 1,
            },
          ],
        },
      ],
      exportLoading: false,
      editVisible: false,
      tableId: '',
      formData: {},
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    importFileUrl() {
      return `//vimi8.oss-cn-shenzhen.aliyuncs.com/template/保函台账导入模板.xlsx?${+new Date()}`
    },
    importUrl() {
      return (
        '/api/credit/import/' +
        queryTrouble('market_project', {
          importKey: this.importKey,
        })
      )
    },
  },
  watch: {},
  created() {
    this.params['submit_client_id.eq'] = this.clientId
    this.getData()
  },
  mounted() {},
  methods: {
    handlerDelete(row) {
      this.$utils.msgbox({
        message: `确定删除项目${row.QYMZ}的保函台账? ${row.BHBH}`,
        beforeClose: () =>
          this.$api
            .deleteData(this.$serviceName, this.tableName, row.id)
            .then(() => {
              this.$message.success('删除成功！')
              this.getData()
            })
            .catch(() => this.$message.error(`删除失败，请重试！`)),
      })
    },
    handlerEdit(row = {}) {
      this.editVisible = true
      this.tableId = row.id || ''
      this.formData = { ...row }
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res] = await this.fetchData(this.params)
      this.loading = false
      const data = (res && res.data) || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.reportDataAdapter)
    },
    reportDataAdapter(row) {
      row.bhType = enumBHType[row.BHLXMJ]
      row.loadStatus = enumLoadStatus[row.ZTMJ]
      row.KHSJ = this.$utils.dateFormat(row.KHSJ, 'yyyy-MM-dd')
      row.DQSJ = this.$utils.dateFormat(row.DQSJ, 'yyyy-MM-dd')
      row.JCSJ = this.$utils.dateFormat(row.JCSJ, 'yyyy-MM-dd')
      return row
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      )
    },
    handleDateChange() {
      this.params.index = 1
      if (this.datePicked && this.datePicked.length === 2) {
        this.params['KHSJ.gte'] = this.datePicked[0]
        this.params['KHSJ.lte'] = `${this.datePicked[1]} 23:59:59`
      } else {
        this.params['KHSJ.gte'] = ''
        this.params['KHSJ.lte'] = ''
      }
      this.getData()
    },
    async exportExcel(filename) {
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: this.params,
        dataAdapter: this.reportDataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
